#!/usr/bin/env python
#-*- coding: utf-8 -*-
import requests
import time
import hashlib
import base64
import json

import rospy
from robot_audio.srv import AIUI, AIUIRequest, AIUIResponse
from robot_audio.msg import voiceMsg
MyAPPId = '5f3ba5da'
MyAPIKey = '56c59a9366962e0d1f14279f797f220a'
awake_flag = True
class AiuiParam(object):
    def __init__(self, APPID, APIKEY):
        self.APPID = APPID
        self.APIKEY = APIKEY
        self.URL = "http://openapi.xfyun.cn/v2/aiui"
        self.AUE = "raw"
        self.AUTH_ID = "2894c985bf8b1111c6728db79d3479ae"
#        DATA_TYPE = "text"
        self.AMPLE_RATE = "16000"
        self.SCENE = "main_box"
        self.RESULT_LEVEL = "complete"
        self.LAT = "22.585706"
        self.LNG = "113.945843"
        self.SAMPLE_RATE = "16000"
    def buildHeader(self, DATA_TYPE):
        curTime = str(int(time.time()))
        param = "{\"result_level\":\""+self.RESULT_LEVEL+"\",\"auth_id\":\""+self.AUTH_ID+"\",\"data_type\":\""+DATA_TYPE+"\",\"sample_rate\":\""+self.SAMPLE_RATE+"\",\"scene\":\""+self.SCENE+"\",\"lat\":\""+self.LAT+"\",\"lng\":\""+self.LNG+"\"}"
        paramBase64 = base64.b64encode(param)
        m2 = hashlib.md5()
        m2.update(self.APIKEY + curTime + paramBase64)
        checkSum = m2.hexdigest()
        header = {
                'X-CurTime': curTime,
                'X-Param': paramBase64,
                'X-Appid': self.APPID,
                'X-CheckSum': checkSum,
                }
        return header
    def msg_processing(self, headers, mytype, data):
        global awake_flag
        if mytype == 'audio':
            message = requests.post(self.URL, headers=headers, data=self.readFile(data))
            num = 1
        else:
            message = requests.post(self.URL, headers=headers, data=data)
            num = 0
        json_data = json.loads(message.text)
        desc = json_data["desc"]
        code = json_data["code"]
        awake_flag = False
        if desc == 'success':
            intent = json_data["data"][num]["intent"]
            print ("识别结果： "+intent["text"].encode('utf-8'))
          #  print (intent["service"])
            if len(intent) > 0:
                if(intent["rc"] == 0):
                    if((intent["service"] == "ZHAO.rosrobot")or(intent["service"] == "ZHAO.yuying_ros")):
                #     print(intent)
                        service = intent["data"]["result"][0]  
                        if(service["cmd"]=="nav"):
                            msg = {"service":"nav", "strValue":["", service["position"].encode('utf-8')], "numValue":[0.0]}
                            print("导航到"+msg['strValue'][1].encode('utf-8'))
                        else:
                            msg = {"service":"control", "strValue":[service["action"].encode('utf-8'),service["text"].encode('utf-8')], "numValue":[float(service["value"])]}
                    elif(intent.has_key("answer")):
                        msg = {"service":"aiui", "strValue":[intent["text"].encode('utf-8'), intent["answer"]["text"].encode('utf-8')], "numValue":[0.0]}
                    else:
                        msg = {"service":"aiui", "strValue":[intent["text"].encode('utf-8'), "这个问题我还不会呢"], "numValue":[0.0]}
                else:
                    if intent["text"].encode('utf-8') == '元宝':
                        msg = {"service":"aiui", "strValue":[" ", "我听着呢"], "numValue":[0.0]}
                        awake_flag = True
                    elif intent["rc"] == 1:
                        msg = {"service":"aiui", "strValue":[" ", "输入异常"], "numValue":[0.0]}
                    elif intent["rc"] == 2:
                        msg = {"service":"aiui", "strValue":[" ", "系统内部异常"], "numValue":[0.0]}
                    elif intent["rc"] == 3:
                        msg = {"service":"aiui", "strValue":[" ", "业务操作失败，没搜索到结果或信源异常"], "numValue":[0.0]}
                    else:
                        msg = {"service":"aiui", "strValue":[" ", "文本没有匹配的技能场景，不能处理该文本"], "numValue":[0.0]}
            else:
                msg = {"service":"aiui", "strValue":[" ", "不好意思，没有听清楚，请再说一次"], "numValue":[0.0]}
                awake_flag = True
        else:
            print("aiui error, errcode is: ", code)
            if code == '10106':
                msg = {"service":"aiui", "strValue":[" ", "不好意思，没有听清楚，请再说一次"], "numValue":[0.0]}
                awake_flag = True
            else:
                nlp = "语义理解出错，错误码为"+str(code)+"请到官网查询原因"
                msg = {"service":"aiui", "strValue":[" ", nlp], "numValue":[0.0]}
        return msg
    def readFile(self, filePath):
        binfile = open(filePath, 'rb')
        data = binfile.read()
        return data

aiui = AiuiParam(APPID=MyAPPId, APIKEY=MyAPIKey)

def callback(req):
    Headers = aiui.buildHeader(req.type)
    message = aiui.msg_processing(headers=Headers,mytype=req.type, data=req.data)
    res = voiceMsg()
    res.service = message["service"]
    res.strValue = message["strValue"]
    res.numValue = message["numValue"]
    print(res.strValue[1])
    return AIUIResponse(res,awake_flag)

if __name__ == "__main__":
    rospy.init_node('voice_aiui')
    server = rospy.Service('voice_aiui',AIUI, callback)
    rospy.spin()
